<template>
	<view class="container">
		<view class="avatar">
			<image class="icon" :src="this.avatar"></image>
		</view>

		<view class="info">
			<view class="detail">
				<view class="top">
					<view class="left">
						<text class="name">{{ petDetails.name }}</text>
						<text class="age">{{ petDetails.ageYear }} Years</text>
						<text class="age">{{ petDetails.ageMonth }} Months</text>
					</view>
					<view class="right">
						<view class="edit" @click="showEditPopup">
							<text class="handle">编辑</text>
						</view>
					</view>
				</view>
				<view class="tags">
					<!-- 					<view class="tag">
						<text class="tag-icon">😺</text>
						<text class="tag-name">品种</text>
						<text class="tag-info">{{ petDetails.breed }}</text>
						<view class="divider"></view>
					</view> -->

					<view class="tag">
						<text class="tag-icon">📖</text>
						<text class="tag-name">品种</text>
						<text class="tag-info">{{ petDetails.breed }}</text>
						<view class="divider"></view>
					</view>
					<view class="tag">
						<text class="tag-icon">⚖️</text>
						<text class="tag-name">体重</text>
						<text class="tag-info">{{ petDetails.weight }}kg</text>
					</view>
<!-- 					<view class="tag">
						<text class="tag-icon">🎨</text>
						<text class="tag-name">疫苗接种情况</text>

					</view> -->
				</view>
			</view>

			<!-- 计划 -->
            <Feeding  :petId="petDetails.id" :data="petDetails.Feeding" @add="addFeeding"></Feeding>
		</view>

		<!-- 编辑信息 -->
		<MyPopup v-if="state.isShowEditPopup" :show="state.isShowEditPopup" @hide="hidePopup">
			<view class="popup">
				<view class="title">编辑</view>
				<MyForm :model="state.editPetDetails" :rules="rules" ref="myFormRef">
					<MyFormItem label="头像">
						<view class="form-avatar">
							<view class="avatar-list">
								<!-- 宠物头像 -->
								<image v-if="state.avatar" class="avatar" :class="{
                  active:
                    state.avatar !== cat
                      ? state.isChooseNewAvatar
                      : true,
                }" :src="state.avatar" @click="chooseAvatar(true, state.avatar)">
								</image>
								<!-- 默认头像 -->
								<image v-if="state.avatar !== cat" class="avatar" :class="{
                  active: !state.isChooseNewAvatar,
                }" :src="cat" @click="chooseAvatar(false)"></image>
							</view>
							<!-- 上传按钮 -->
							<image class="icon" src="@/assets/svgs/upload.svg" @click="uploadAvatar">上传图片</image>
						</view>
					</MyFormItem>
					<!-- 					<MyFormItem label="性别">
						<MyRadioGroup name="sex" v-model="state.editPetDetails.sex">
							<MyRadio value="公" label="公" @updateModelValue="updateModelValue" obj="sex"
								:selectValue="state.editPetDetails.sex" />
							<MyRadio value="母" label="母" @updateModelValue="updateModelValue" obj="sex"
								:selectValue="state.editPetDetails.sex" />
						</MyRadioGroup>
					</MyFormItem> -->
					<MyFormItem label="昵称">
						<MyInput name="name" type="text" @updateModelValue="updateModelValue"
							:modelValue="state.editPetDetails.name" v-model="editPetDetails.name" obj="name" />
					</MyFormItem>
					<MyFormItem label="岁数">
						<MyInput name="year" type="text" @updateModelValue="updateModelValue"
							:modelValue="state.editPetDetails.ageYear" v-model="editPetDetails.ageYear" obj="ageYear" />
					</MyFormItem>
					<MyFormItem label="月份">
						<MyInput name="month" type="text" @updateModelValue="updateModelValue"
							:modelValue="state.editPetDetails.ageMonth" v-model="editPetDetails.ageMonth"
							obj="ageMonth" />
					</MyFormItem>
					<MyFormItem label="品种">
						<MyInput name="breed" type="text" @updateModelValue="updateModelValue"
							:modelValue="state.editPetDetails.breed" obj="breed" v-model="editPetDetails.breed" />
					</MyFormItem>

					<!-- 					<MyFormItem label="品种"> -->
					<!-- <MySelect name="cate" v-model="state.editPetDetails.category" :height="'8rem'">
              <MyOption v-for="cate in state.categoryList" :key="cate.id" :label="cate.label" :value="cate.id">
              </MyOption>
            </MySelect> -->
					<!-- 						<MyInput name="cate" type="text" @updateModelValue="updateModelValue"
							:modelValue="state.editPetDetails.cate" obj="cate" />
					</MyFormItem> -->

					<MyFormItem label="体重/kg" prop="weight">
						<MyInput name="weight" type="number" @updateModelValue="updateModelValue"
							:modelValue="state.editPetDetails.weight" obj="weight" v-model="editPetDetails.weight" />
					</MyFormItem>

					<button class="submit" @click="handleEditPetSubmit">完成</button>
				</MyForm>
			</view>
		</MyPopup>

		<MyMessage ref="myMessageRef"></MyMessage>
	</view>
</template>

<script>
	// import { Pet } from "@/typings/pet";
	// import { Plan } from "@/typings/plan";
	import {
		onLoad
	} from "@dcloudio/uni-app";
	import {
		mapGetters,
		mapActions
	} from 'vuex';


	// import { usePetStore } from "@/store/pet";
	import cat from "@/assets/images/cat.png";
	// import { getColors, getPetCategories } from '@/apis/pet'
	import MyPopup from '@/components/MyPopup/MyPopup.vue'
	import MyDialog from '@/components/MyDialog/MyDialog.vue'
	import MyMessage from '@/components/MyMessage/MyMessage.vue'
	import MyForm from '@/components/MyForm/MyForm.vue'
	import MyRadioGroup from '@/components/MyRadioGroup/MyRadioGroup.vue'
	import MyRadio from '@/components/MyRadio/MyRadio.vue'
	import MyInput from '@/components/MyInput/MyInput.vue'
	import MyFormItem from '@/components/MyFormItem/MyFormItem.vue'

	export default {
		data() {
			return {
				myFormRef: null,
				myMessageRef: null,
				// petStore: usePetStore(),
				state: {
					avatar: cat,
					isShowEditPopup: false,
					petId: "",
					editPetDetails: {
						// avatar: cat,
						id: "",
						// avatar: cat,
						name: "",
						breed: "",
						ageYear: "",
						ageMonth: "",
						// sex: "母",
						// category: "cat",
						// color: "白",
						weight: "1",
						// plans: [],
						photoUrl: "http://dummyimage.com/400x400"
					},
					isChooseNewAvatar: false,
					planList: [{
							dueTime: "2023/10/08 14:15",
							avatar: "",
							title: "喂罐头",
							notes: "半罐",
							time: "40",
						},
						{
							dueTime: "2023/10/08 16:15",
							avatar: "",
							title: "喂化毛膏",
							notes: "5cm",
							time: "40",
						},
					],
					colorList: [],
					categoryList: [],
				},
				rules: {
					weight: [{
						required: true,
						message: "请输入体重",
					}, ],
				},
				petDetails: {
					// avatar: cat,
					id: "",
					// avatar: cat,
					name: "",
					breed: "",
					ageYear: "",
					ageMonth: "",
					// sex: "母",
					// category: "cat",
					// color: "白",
					weight: "",
					// plans: [],
					photoUrl: "http://dummyimage.com/400x400"
				},
				petColor: "",
				petCategory: "",
			};
		},
		components: {
			MyPopup,
			MyDialog,
			MyMessage,
			MyForm,
			MyRadioGroup,
			MyRadio,
			MyInput,
			MyFormItem
		},
		computed: {
			...mapGetters('pet', ['getPetById']), // 'pet' 是模块名，getPetById 是 getter 名
			petDetailsComputed() {
				// if (this.state.petId) {
				//   const pet = this.petStore.getPetById(this.state.petId);
				//   if (pet) {
				//     return pet;
				//   } else {
				//     this.$nextTick(() => {
				//       this.$refs.myMessageRef.show({
				//         message: "查找不到该宠物信息",
				//         type: "error",
				//         complete() {
				//           uni.navigateTo({ url: "/pages/pet/pet" });
				//         },
				//       });
				//     });
				//     return {};
				//   }
				// } else {
				//   return {};
				// }
			},

			cat() {
				return cat
			}
		},
		watch: {
			petDetailsComputed(newValue) {
				this.state.editPetDetails = {
					...newValue
				};
			},
		},
		onLoad(options) {
			// 在小程序中使用 options 获取 URL 参数
			//    const pages = getCurrentPages();
			//    const currentPage = pages[pages.length - 1];
			// console.log(currentPage)
			this.petId = options.id;
			console.log("11111111", this.petId);
			if (this.petId) {
				this.petDetails = this.getPetById(this.petId);
				console.log("petDetails", this.petDetails);
				
				this.state.editPetDetails.id = this.petId;
				if (!this.petDetails) {
					this.$refs.myMessageRef.show({
						message: '查找不到该宠物信息',
						type: 'error',
					});
					this.$router.push('/pages/pet/pet');
				}
			}
		},
		methods: {
			...mapActions('pet', ['editPet']),
			updateModelValue(obj, val) {
				this.state.editPetDetails[`${obj}`] = val
			},
			getColorList() {
				// getColors().then(({ colors }) => {
				//   this.state.colorList = colors;
				// });
			},
			getPetCategoryList() {
				// getPetCategories({ type: this.petDetails.category }).then(({ pet_categories }) => {
				//   this.state.categoryList = pet_categories;
				// });
			},
			hidePopup() {
				this.state.isShowEditPopup = false;
			},
			showEditPopup() {
				this.state.isShowEditPopup = true;
				// console.log("Current pet details: ", this.petDetails);
				// if (this.petDetails && Object.keys(this.petDetails).length > 0) {
				// 	this.state.editPetDetails = JSON.parse(JSON.stringify(this.petDetails));
				// 	this.isShowEditPopup = true;
				// 	console.log("Edit details set for: ", this.editPetDetails);
				// } else {
				// 	console.error("No pet details available for editing.");
				// }
			},
			chooseAvatar(isChooseNewAvatar, newAvatarUrl) {
				this.state.isChooseNewAvatar = isChooseNewAvatar;
				if (isChooseNewAvatar && newAvatarUrl) {
					this.state.editPetDetails.avatar = newAvatarUrl;
				} else {
					this.state.editPetDetails.avatar = cat;
				}
			},
			handleEditPetSubmit() {
				this.$refs.myFormRef.validate((valid) => {
					if (valid) {
						// 页面直接触发处理结果 - 第一种
						const param = {
							...this.state.editPetDetails
						}


						// 这个是触发actions里面的新增 - 第二种 -- 方便统一全局管理
						console.log(this.state.editPetDetails)
						this.editPet(this.state.editPetDetails);
						this.hidePopup();
						this.$refs.myMessageRef.show({
							message: "修改成功",
						});

					}
				});
				// this.$refs.myFormRef.validate((valid) => {
				// 	if (valid) {
				// 		this.hidePopup();
				// 		// this.petStore.editPetById(this.state.editPetDetails.id, this.state.editPetDetails);
				// 		this.$refs.myMessageRef.show({
				// 			message: "修改成功",
				// 		});
				// 	}
				// });
			},
			uploadAvatar() {
				uni.chooseMedia({
					count: 1,
					mediaType: ["image"],
					sizeType: ["original"],
					success(res) {
						const file = res.tempFiles[0];
						console.log(res);

						if (/.png$/.test(file.tempFilePath)) {
							this.state.editPetDetails.avatar = file.tempFilePath;
							this.state.isChooseNewAvatar = true;
						} else {
							this.$refs.myMessageRef.show({
								message: "请上传 png 类型的图片",
								type: "error",
							});
						}
					},
				});
			},
			addPlan(plan) {
				if (this.petDetails) {
					const pet = {
						...this.petDetails
					};
					pet.plans.push(plan);
					// this.petStore.editPetById(pet.id, pet);
				}
			},
		},
	};
</script>

<style lang="less" scoped>
	@import "@/static/styles/base.less";

	.container {
		.avatar {
			width: 100%;
			height: 40vh;
			background: @my-color-primary;
			display: flex;
			align-items: center;
			justify-content: center;
			position: relative;

			.icon {
				width: 100%;
				height: 100%;
			}

			.upload {
				width: 2rem;
				height: 2rem;
				position: absolute;
				right: 1.5rem;
				bottom: 15%;
			}
		}

		.info {
			width: 100%;
			height: 70vh;
			position: relative;
			margin-top: -2rem;
			box-sizing: border-box;
			.handle {
				color: @my-color-primary;
				font-size: 0.8rem;
			}
			.detail {
				background: #fff;
				padding: 1rem 1.5rem;
				border-radius: 1.3rem 1.3rem 2rem 0;
				margin-bottom: 2rem;
				position: relative;

				&::after {
					content: "";
					position: absolute;
					bottom: -2rem;
					left: 0;
					background: #fff;
					display: block;
					width: 2rem;
					height: 2rem;
				}

				&::before {
					content: "";
					position: absolute;
					bottom: -2rem;
					left: 0;
					background: @my-background-color;
					display: block;
					width: 2rem;
					height: 2rem;
					z-index: 2;
					border-radius: 2rem 0 0 0;
				}

				.top {
					display: flex;
					justify-content: space-between;
					align-items: center;

					.left {
						display: flex;
						flex-direction: column;

						.name {
							font-weight: bold;
							font-size: 1.5rem;
						}

						.age {
							color: @my-text-color-grey;
						}
					}

					.right {
						.edit {
							width: 2rem;
							height: 2rem;
							display: flex;
							justify-content: center;
							align-items: center;

							.icon {
								width: 80%;
								height: 80%;
							}
						}
					}
				}

				.tags {
					display: flex;

					.tag {
						width: 100%;
						display: flex;
						flex-direction: column;
						align-items: center;
						padding-top: 1rem;
						position: relative;

						.tag-icon {
							margin-bottom: 0.3rem;
							font-size: 1.6rem;
						}

						.tag-name {
							color: @my-text-color-grey;
							font-size: 0.6rem;
							margin-bottom: 0.3rem;
						}

						.tag-info {
							font-weight: bold;
						}

						.divider {
							position: absolute;
							right: 0;
							top: 50%;
							transform: translateY(-50%);
							width: 1.5px;
							height: 1rem;
							background: #e7e7e792;
						}
					}
				}
			}
		}

		.popup {
			width: 60vw;

			.title {
				font-weight: bold;
				font-size: 1.2rem;
				color: @my-color-primary;
				margin-bottom: 1rem;
			}

			.form-avatar {
				display: flex;
				justify-content: space-between;
				align-items: center;

				.avatar-list {
					display: flex;

					.avatar {
						width: 3rem;
						height: 3rem;
						border-radius: 50%;
						box-sizing: border-box;
						margin-right: 1rem;
						opacity: 0.3;

						&.active {
							opacity: 1;
						}
					}
				}

				.icon {
					width: 2rem;
					height: 2rem;
				}
			}

			.submit {
				background: @my-color-primary;
				color: #fff;
				font-size: 1rem;
				border-radius: 0.8rem;
				margin-top: 2rem;

				&::after {
					border: none;
				}
			}
		}
	}
</style>